package com.huike.xingxing;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkError;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.huike.xingxing.activity.BaseActivity;
import com.huike.xingxing.activity.HomeActivity;
import com.huike.xingxing.api.Api;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import androidx.appcompat.app.AppCompatActivity;

/**
 * 登陆界面
 */
public class MainActivity extends BaseActivity {

    private EditText et_main_user;
    private EditText et_main_pwd;
    private Spinner sp_home;
    private RequestQueue queue;
    private String roles = "student";//学生


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queue = Volley.newRequestQueue(this);
        initView();
        final String[] role = new String[]{"家长","教师"};

        SpinnerAdapter adapter = new SpinnerAdapter(this,
                android.R.layout.simple_list_item_1, role);
        sp_home.setAdapter(adapter);

      sp_home.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
          @Override
          public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
              if(position == 0){
                  roles = "student";
              }else  if(position == 1){
                  roles = "mom";
              }

          }

          @Override
          public void onNothingSelected(AdapterView<?> parent) {

          }
      });
    }

    public void RegisterData(){


        String pwd = et_main_pwd.getText().toString().trim();
        final String user = et_main_user.getText().toString().trim();

        if(TextUtils.isEmpty(pwd)){
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(user)){
            Toast.makeText(this, "账户不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoading();

        JSONObject object = new JSONObject();

        try {
            object.put("password",pwd);
            object.put("name",user);
            object.put("authtype",roles);
            object.put("head_image","");

            Log.e("---", "RegisterData: "+object.toString() );
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest request = new JsonObjectRequest(1, Api.locaApi + "register", object.toString(), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                hide();
                try {
                    String uuid = jsonObject.getString("msg");
                    Log.e("---",jsonObject.toString());
                    String code = jsonObject.getString("data");


                    if(code.equals("注册成功") && !TextUtils.isEmpty(code)){
                        Toast.makeText(MainActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();

                        //添加缓存
                        SharedPreferences userIfno = getSharedPreferences("user_ifno", MODE_PRIVATE);
                        userIfno.edit().putString("data",roles).putString("username",user).putString("uid",uuid).commit();

                        startActivity(new Intent(MainActivity.this, HomeActivity.class));
                    }else{
                        Toast.makeText(MainActivity.this, code, Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                    hide();
                Toast.makeText(MainActivity.this, "网络异常！", Toast.LENGTH_SHORT).show();
            }
        });

        queue.add(request);

    }
    public void LoginData(){


        String pwd = et_main_pwd.getText().toString().trim();
        final String user = et_main_user.getText().toString().trim();


        if(TextUtils.isEmpty(pwd)){
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(user)){
            Toast.makeText(this, "账户不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        showLoading();

        JSONObject object = new JSONObject();

        try {
            object.put("password",pwd);
            object.put("name",user);
            object.put("authtype",roles);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.e("---",pwd +"-" + user + "-" +roles);

        JsonObjectRequest request = new JsonObjectRequest(1, Api.locaApi + "login", object.toString(), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                hide();
                Log.e("---",jsonObject.toString());
                try {


                    String uuid = jsonObject.getString("msg");
                    String code = jsonObject.getString("data");



                    if(!code.equals("fail")){

                        JSONObject data = jsonObject.getJSONObject("data");

                        Toast.makeText(MainActivity.this, "登陆成功！", Toast.LENGTH_SHORT).show();
                        //添加用户角色缓存
                        SharedPreferences userIfno = getSharedPreferences("user_ifno", MODE_PRIVATE);
                        userIfno.edit().putString("data",roles).putString("username",user).putString("uuid",data.getString("id"))
                                .putString("head_image",data.getString("head_image"))
                                .commit();

                        startActivity(new Intent(MainActivity.this, HomeActivity.class));
                    }else{
                        Toast.makeText(MainActivity.this, "登陆失败！", Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                    hide();
                checkError(volleyError);
            }
        });

        queue.add(request);

    }




    //登陆
    public void login(View v) {
        LoginData();
    }

    //注册
    public void register(View v) {
        RegisterData();

    }

    private void initView() {
        et_main_user = (EditText) findViewById(R.id.et_main_user);
        et_main_pwd = (EditText) findViewById(R.id.et_main_pwd);
        sp_home =  findViewById(R.id.sp_home);
    }

    //自定义 Spinner 样式
    private class SpinnerAdapter extends ArrayAdapter<String> {
        Context context;
        String[] items = new String[] {};

        public SpinnerAdapter(final Context context,
                              final int textViewResourceId, final String[] objects) {
            super(context, textViewResourceId, objects);
            this.items = objects;
            this.context = context;
        }

        @Override
        public View getDropDownView(int position, View convertView,
                                    ViewGroup parent) {

            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
                convertView = inflater.inflate(
                        android.R.layout.simple_spinner_item, parent, false);
            }

            TextView tv = (TextView) convertView
                    .findViewById(android.R.id.text1);
            tv.setText(items[position]);
            tv.setGravity(Gravity.START);
            tv.setTextColor(Color.GRAY);
            tv.setPadding(20,10,0,10);
            tv.setTextSize(20);
            return convertView;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
                convertView = inflater.inflate(
                        android.R.layout.simple_spinner_item, parent, false);
            }

            TextView tv = (TextView) convertView
                    .findViewById(android.R.id.text1);
            tv.setText(items[position]);
            tv.setGravity(Gravity.START);
            tv.setTextColor(Color.WHITE);
            tv.setTextSize(23);
            return convertView;
        }
    }

}
